//
//  ChoosePhoto.m
//  HB
//
//  Created by 陶秋安 on 16/5/12.
//  Copyright © 2016年 孙智慧. All rights reserved.
//

#import "ChoosePhoto.h"



@implementation ChoosePhoto

-(void)setBackBarButton
{

}
 
- (void)setNavigationRight:(NSString *)imageName sel:(SEL)sel
{
    UIButton *btn=[self customButton:@"shareicon" selector:@selector(takePictureClick)];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    self.navigationItem.rightBarButtonItem = item;
}

- (void)setNavigationTitleImage:(NSString *)imageName
{
    self.navigationItem.title = @"个人头像";
}

- (void)viewDidLoad {
    [super viewDidLoad];

    _scrollview=[[UIScrollView alloc]initWithFrame:self.view.bounds];
    
    [self.view addSubview:_scrollview];
 
    //(2)使用构造方法
    UIImage *image=[UIImage imageNamed:@"550-01.jpg"];
    
    CGFloat imageView_X = (image.size.width > self.view.frame.size.width) ? self.view.frame.size.width : image.size.width;
    CGFloat imageView_Y;
    CGFloat origin;
    if(image.size.width > self.view.frame.size.width){
        origin = self.view.frame.size.width/image.size.width;
        imageView_Y = image.size.height*origin;
    }
    else
    {
        imageView_Y =image.size.height;
    }
    
    _imageview = [[UIImageView alloc]initWithFrame:CGRectMake((self.view.frame.size.width-imageView_X)/2, (self.view.frame.size.height-imageView_Y)/2, imageView_X, imageView_Y)];
    
    _imageview.contentMode =UIViewContentModeScaleAspectFit;
    UIImage *originImage=[[UIImage alloc]initWithCGImage:image.CGImage];
    [_imageview setImage:originImage];
    //调用initWithImage:方法，它创建出来的imageview的宽高和图片的宽高一样
    [_scrollview addSubview:_imageview];
    
    //设置UIScrollView的滚动范围和图片的真实尺寸一致
    _scrollview.contentSize=image.size;
    
    
    //设置实现缩放
    //设置代理scrollview的代理对象
    _scrollview.delegate=self;
    //设置最大伸缩比例
    _scrollview.maximumZoomScale=2.0;
    //设置最小伸缩比例
    _scrollview.minimumZoomScale=1;

}

//实现图片在缩放过程中居中
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?(scrollView.bounds.size.width - scrollView.contentSize.width)/2 : 0.0;
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?(scrollView.bounds.size.height - scrollView.contentSize.height)/2 : 0.0;
    _imageview.center = CGPointMake(scrollView.contentSize.width/2 + offsetX,scrollView.contentSize.height/2 + offsetY);
}

//告诉scrollview要缩放的是哪个子控件
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _imageview;
}



//从相册获取图片
-(void)takePictureClick
{

    UIActionSheet* actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:@"请选择文件来源"
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"照相机",@"本地相簿",nil];
    [actionSheet showInView:self.view];
    
}

#pragma mark -
#pragma UIActionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"buttonIndex = [%ld]",(long)buttonIndex);
    switch (buttonIndex) {
        case 0://照相机
        {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            //            [self presentModalViewController:imagePicker animated:YES];
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
            break;
        case 1://本地相簿
        {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //            [self presentModalViewController:imagePicker animated:YES];
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(__bridge NSString *)kUTTypeImage]) {
        UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
        [self performSelector:@selector(saveImage:)  withObject:img afterDelay:0.5];
    }
    //    [picker dismissModalViewControllerAnimated:YES];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //    [picker dismissModalViewControllerAnimated:YES];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)saveImage:(UIImage *)image {
    //    NSLog(@"保存头像！");
    //    [userPhotoButton setImage:image forState:UIControlStateNormal];
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
    NSLog(@"imageFile->>%@",imageFilePath);
    success = [fileManager fileExistsAtPath:imageFilePath];
    if(success) {
        success = [fileManager removeItemAtPath:imageFilePath error:&error];
    }
    //    UIImage *smallImage=[self scaleFromImage:image toSize:CGSizeMake(80.0f, 80.0f)];//将图片尺寸改为80*80
    UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(93, 93)];
    [UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:imageFilePath atomically:YES];//写入文件
    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//读取图片文件
    //    [userPhotoButton setImage:selfPhoto forState:UIControlStateNormal];
    _imageview.image = selfPhoto;
    
    [self uploadAction];
}

// 改变图像的尺寸，方便上传服务器
- (UIImage *) scaleFromImage: (UIImage *) image toSize: (CGSize) size
{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

//2.保持原来的长宽比，生成一个缩略图
- (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
    UIImage *newimage;
    if (nil == image) {
        newimage = nil;
    }
    else{
        CGSize oldsize = image.size;
        CGRect rect;
        if (asize.width/asize.height > oldsize.width/oldsize.height) {
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            rect.size.height = asize.height;
            rect.origin.x = (asize.width - rect.size.width)/2;
            rect.origin.y = 0;
        }
        else{
            rect.size.width = asize.width;
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = (asize.height - rect.size.height)/2;
        }
        UIGraphicsBeginImageContext(asize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
        [image drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
}


//上传头像
- (void)uploadAction
{
    NSString *url1= [FxGlobal getServiceUrl:@"Mine" andFuncName:@"ImgUpload"];
    
    NSData *imgData=UIImageJPEGRepresentation(_imageview.image, 0.9f);
    
    NSString *boundary = @"0xKhTmLbOuNdArY";//边界
    
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary, nil];
    
    NSURL *url=[NSURL URLWithString:url1];
    
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    
    [request addValue:contentType forHTTPHeaderField:@"Content-Type"];
    
    [request setHTTPMethod:@"POST"];
    
    NSMutableData *body = [NSMutableData data];
    
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\"iphonefile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:[NSData dataWithData:imgData]];
    
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [request setHTTPBody:body];
    
    NSOperationQueue *queue=[[NSOperationQueue alloc] init];
    
    [NSURLConnection sendAsynchronousRequest:request queue:queue
                           completionHandler:^(NSURLResponse *respone,
                                               NSData *data,
                                               NSError *error)
     {
         if ([data length]>0 && error==nil)
         {
             
             
             NSError *err;
             
             NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
             
             NSString *fileName=  [dic objectForKey:@"fileName"];
             
             [self myTask:fileName];
             
         }
     }];
}

- (void)myTask:(NSString *)fileName
{
    
    operation=[[LoginOperation alloc] initWithDelegate:self];
    
    NSString *url= [FxGlobal getServiceUrl:@"Mine" andFuncName:@"UploadHeadImg"];
    
    NSString *djID= [Common getUserDefaults:@"djID"];
    
    NSString *imgUrl=[NSString stringWithFormat:@"http://%@/HeadImg/%@",serviceip,fileName];
    
    NSString *md5Str= [NSString stringWithFormat: @"djID=%@&imgUrl=%@&key=tqa",djID,imgUrl];
    
    NSString *sign = [Common createMD5:md5Str];
    
    NSString *body=[NSString stringWithFormat:@"{\"djID\":\"%@\",\"imgUrl\":\"%@\",\"sign\":\"%@\",\"clicentid\":\"1\"}",djID,imgUrl,sign];
    
    NSDictionary *dictInfo = @{@"url":url,@"body":body};
    
    [operation setOpInfo:dictInfo];
    
    [operation post];
    
}

-(void) opSuccessForPost:(id)data
{
    operation=nil;
    
    NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSDictionary *data1 = [dataStr objectFromJSONString];
    
    NSString *v=[data1 objectForKey:@"result"];
    
    if([v isEqualToString:@"1"])
    {
        
        
    }
    
}


@end
